package com.fancy.social.service.impl;

import com.fancy.social.dto.PrivateMessageCreateDTO;
import com.fancy.social.entity.PrivateMessage;
import com.fancy.social.mapper.PrivateMessageMapper;
import com.fancy.social.service.PrivateMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class PrivateMessageServiceImpl implements PrivateMessageService {

    @Autowired
    private PrivateMessageMapper privateMessageMapper;

    @Override
    public void sendMessage(Long senderId, PrivateMessageCreateDTO privateMessageCreateDTO) {
        PrivateMessage privateMessage = new PrivateMessage();
        privateMessage.setSenderId(senderId);
        privateMessage.setReceiverId(privateMessageCreateDTO.getReceiverId());
        privateMessage.setContent(privateMessageCreateDTO.getContent());
        privateMessage.setMessageType(privateMessageCreateDTO.getMessageType() != null ? privateMessageCreateDTO.getMessageType() : 1);
        privateMessage.setIsRead(false);
        privateMessage.setCreateTime(LocalDateTime.now());
        privateMessageMapper.insert(privateMessage);
    }

    @Override
    public void readMessage(Long userId, Long messageId) {
        PrivateMessage privateMessage = privateMessageMapper.selectById(messageId);
        if (privateMessage != null && privateMessage.getReceiverId().equals(userId)) {
            privateMessage.setIsRead(true);
            privateMessage.setReadTime(LocalDateTime.now());
            privateMessageMapper.updateById(privateMessage);
        }
    }
}

